package com.jmtao.common;

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.config.ConfigFileApplicationListener;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.SystemEnvironmentPropertySource;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * description: 解决多网卡无法获取正确ip的bug，
 * 忽略所有的网卡地址，通过hostname从/etc/hosts中获取对应的ip。
 * 所以需要做下列操作
 * 1. 设置hostname
 * 2. 在/etc/hosts中添加 ip hostname
 *
 * @author K
 */
public class IpAndHostChooser implements BeanPostProcessor, EnvironmentPostProcessor, Ordered {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Map<String, Object> ignoredInterfaces = new HashMap<>(1);
        ignoredInterfaces.put("spring.cloud.inetutils.ignoredInterfaces", Arrays.asList(".*"));
        SystemEnvironmentPropertySource systemEnvironmentPropertySource = new SystemEnvironmentPropertySource("systemEnvironment", ignoredInterfaces);
        environment.getPropertySources().addLast(systemEnvironmentPropertySource);

    }

    @Override
    public int getOrder() {
        return ConfigFileApplicationListener.DEFAULT_ORDER - 2;
    }
}
